package com.tz.farmer.controller;


import com.alibaba.fastjson.JSONObject;
import com.smartPark.msframe.result.ResultEx;

import com.tz.farmer.config.ExecutableClientConfig;
import com.tz.farmer.mapper.FarmerUserInfoMapper;
import com.tz.farmer.service.FarmerUserInfoService;
import com.tz.farmer.service.UserLoginService;
import com.tz.farmer.so.ZzdLonginSo;
import com.tz.farmer.util.HttpUtils;
import com.tz.farmer.util.ZzdUtil;
import io.swagger.annotations.Api;

import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @description: 浙政钉登陆
 * @name BusinessController
 * @author: xhj
 * @date: 2021/11/26
 * @version V1.0
 */
@Controller
@RequestMapping("zzdLogin")
@Api(value = "浙政钉登陆", tags = "浙政钉登陆")
public class ZzdLoginController {

    private static Logger logger = LoggerFactory.getLogger(ZzdLoginController.class);

    @Resource
    FarmerUserInfoService farmerUserInfoService;

    @Resource
    UserLoginService userLoginService;
    @Resource
    FarmerUserInfoMapper farmerUserInfoMapper;

    /**
     * @description:  浙政钉登陆
     * @name businessInfo
     * @author: xhj
     * @date: 2021/11/26 11:35
     * @version V1.0
     */
    @ApiOperation("获取浙政钉用户信息")
    @GetMapping("userInfo")
    public String getUserInfo(String code) {
        logger.info("扫码之后回调接口传参"+code);
        try {
            //获取token
            String accessToken=ZzdUtil.getAccessToken();
            logger.info("获取的token："+accessToken);
            //获取用户信息
            Map<String,String> map=new HashMap<>();
            map.put("access_token", accessToken);
            map.put("code", code);
            String apiResult=ExecutableClientConfig.doPost("/rpc/oauth2/getuserinfo_bycode.json",map);
            logger.info("获取人员信息返回数据"+apiResult);
            JSONObject jsonObj = JSONObject.parseObject(apiResult);
            String content = jsonObj.get("content")+"";
            String data = JSONObject.parseObject(content).get("data")+"";
            String accountId = JSONObject.parseObject(data).get("accountId")+"";
            logger.info("用户code"+accountId);
            List<Map<String,Object>> list=farmerUserInfoService.ifHave(accountId);
            if(list!=null&&list.size()>0){
                List<String> funs=farmerUserInfoMapper.selectFunByUser(Integer.valueOf(list.get(0).get("id")+""));
                String funIds="";
                for(String s:funs){
                    funIds+=s+",";
                }
                if(StringUtils.isNotBlank(funIds)){
                    funIds=funIds.substring(0,funIds.length()-1);
                }
                return "redirect:https://scaq.tzscjg.cn:18888/farmerweb/#/shouye/index?funs="+funIds+"&userAccount="+list.get(0).get("user_account")+"&token=123456&flag=1";
            }else{
                return "redirect:https://scaq.tzscjg.cn:18888/farmerweb/#/bind?employeeCode="+accountId;
            }
        }catch (Exception e){
            logger.error("获取用户信息异常",e.getMessage());
            return null;
        }
    }

    /**
     * @description:  浙政钉用户和台渔链用户绑定
     * @name businessInfo
     * @author: xhj
     * @date: 2021/11/26 11:35
     * @version V1.0
     */
    @ApiOperation("浙政钉用户和台渔链用户绑定")
    @GetMapping("updateUserInfo")
    @ResponseBody
    @ApiImplicitParams({
            @ApiImplicitParam(name = "phone", value = "电话号码", defaultValue = ""),
            @ApiImplicitParam(name = "employeeCode", value = "员工code", defaultValue = "")

    })
    public String updateUserInfo(ZzdLonginSo zzdLonginSo) {
        logger.info("收到的参数 phone："+zzdLonginSo.getPhone()+",employeeCode:"+zzdLonginSo.getEmployeeCode());
        try {
            farmerUserInfoService.updateUserInfo(zzdLonginSo.getPhone(),zzdLonginSo.getEmployeeCode());
            List<Map<String,Object>> list=farmerUserInfoService.selectUserInfoByPhone(zzdLonginSo.getPhone());
            List<String> funs=farmerUserInfoMapper.selectFunByUser(Integer.valueOf(list.get(0).get("id")+""));
            String funIds="";
            for(String s:funs){
                funIds+=s+",";
            }
            if(StringUtils.isNotBlank(funIds)){
                funIds=funIds.substring(0,funIds.length()-1);
            }
            return "https://scaq.tzscjg.cn:18888/farmerweb/#/shouye/index?funs="+funIds+"&userAccount="+list.get(0).get("user_account")+"&token=123456&flag=1";
        }catch (Exception e){
            logger.error("绑定失败",e.getMessage());
            return null;
        }
    }


    /**
     * @description:  校验手机号是否存在
     * @name businessInfo
     * @author: xhj
     * @date: 2021/11/26 11:35
     * @version V1.0
     */
    @ApiOperation("校验手机号是否存在")
    @PostMapping("phoneExist")
    @ResponseBody
    @ApiImplicitParams({
            @ApiImplicitParam(name = "phone", value = "电话号码", defaultValue = ""),
    })
    public ResultEx phoneExist(@RequestBody ZzdLonginSo zzdLonginSo) {
        try {
            return farmerUserInfoService.phoneExist(zzdLonginSo.getPhone());
        }catch (Exception e){
            logger.error("校验失败",e.getMessage());
            return ResultEx.builder().makeFailedResult("校验失败");
        }
    }
}
